<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { IAddressPoolGroup } from './address-pool-collection/types'
import type { DnsLinesListItem, GtmInstanceItem } from '@/apis/model/dns'
import { Message } from '@arco-design/web-vue'
import { omit } from 'lodash-es'
import { v4 as uuidV4 } from 'uuid'
import {
  addDnsAuthorityGtmStrategyApi,
  getDnsAuthorityGtmStrategyApi,
  updateDnsAuthorityGtmStrategyApi,
} from '@/apis/modules/dns'
import AddressPoolCollection from './address-pool-collection'

interface IEmits {
  (e: 'update:visible', value: boolean): void
  (e: 'reload'): void
}
interface IProps {
  record?: GtmInstanceItem
  linesData: DnsLinesListItem[]
}
const props = defineProps<IProps>()
const emits = defineEmits<IEmits>()
const route = useRoute()
const visible = defineModel<boolean>('visible', { required: true })
const title = computed(() => (props?.record?.id ? '编辑策略' : '新建策略'))
const formRef = ref<FormInstance>()
const addressPoolView = ref()
const formState = reactive({
  line: undefined,
  priority: undefined,
  status: 1,
})
const addressGroups = ref<IAddressPoolGroup[]>([
  {
    uuid: uuidV4(),
    name: '地址池集合1',
    edit: false,
    address_pool_ids: [
      {
        uuid: uuidV4(),
        id: '',
      },
    ],
  },
])
const rules: Record<string, FieldRule> = {
  line: { required: true, message: '请求来源不能为空' },
  priority: { required: true, message: '优先级不能为空' },
}
const loading = ref(false)

async function getDetail() {
  loading.value = true
  await getDnsAuthorityGtmStrategyApi({ id: props?.record?.id })
    .then((res) => {
      Object.assign(formState, res)
      addressGroups.value = res.address_pool_sets.map((item) => {
        return {
          uuid: uuidV4(),
          name: item.name,
          edit: false,
          address_pool_ids: item.address_pools.map(v => ({
            uuid: uuidV4(),
            id: v.id,
          })),
        }
      })
    })
    .finally(() => (loading.value = false))
}
async function handleSubmit() {
  const error = await formRef.value?.validate()
  const error1 = await addressPoolView.value?.validate()
  if (error || !error1)
    return false
  const data = {
    ...omit(formState, ['created_at', 'updated_at', 'address_pool_sets']),
    instance_id: route.params.id,
    pool_sets: addressGroups.value.map(item => ({
      name: item.name,
      address_pool_ids: item.address_pool_ids.map(v => v.id),
    })),
  }
  loading.value = true
  const apiPath = props?.record?.id
    ? updateDnsAuthorityGtmStrategyApi
    : addDnsAuthorityGtmStrategyApi
  apiPath(data)
    .then(() => {
      Message.success('操作成功')
      emits('reload')
    })
    .finally(() => (loading.value = false))
}
function handleOpen() {
  if (props?.record?.id)
    getDetail()
}
function handleClose() {
  emits('update:visible', false)
  formRef.value?.resetFields()
  addressPoolView.value?.reset()
}
</script>

<template>
  <a-drawer
    v-model:visible="visible"
    :title="title"
    :width="480"
    ok-text="保存"
    :mask-closable="false"
    :ok-loading="loading"
    :on-before-ok="handleSubmit"
    @before-open="handleOpen"
    @before-close="handleClose"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="rules"
    >
      <a-form-item
        label="请求来源"
        field="line"
        asterisk-position="end"
      >
        <a-cascader
          v-model="formState.line"
          :options="linesData"
          check-strictly
          expand-trigger="hover"
          :field-names="{
            label: 'name',
            value: 'code',
            children: 'children',
          }"
          placeholder="请选择请求来源"
        />
      </a-form-item>
      <address-pool-collection
        ref="addressPoolView"
        v-model="addressGroups"
        class="mb-6"
      />
      <a-form-item
        field="priority"
        hide-asterisk
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            优先级
            <span class="text-4 text-[#FA5566]">*</span>
            <a-tooltip
              content="同一请求来源下优先级生效。"
              :show-arrow="false"
              position="top"
            >
              <i-icons-question
                class="question-icon cursor-pointer !text-[#86909c]"
              />
            </a-tooltip>
          </div>
        </template>
        <a-input-number
          v-model.number="formState.priority"
          class="w-full"
          :hide-button="true"
          :min="1"
          :max="999"
          placeholder="请输入优先级"
        />
      </a-form-item>
      <a-form-item
        field="status"
        label="状态"
        hide-asterisk
      >
        <a-switch
          v-model="formState.status"
          :checked-value="1"
          :unchecked-value="2"
          size="small"
        />
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<style lang="less" scoped>
.question-icon {
  color: #86909c;
  width: 14px !important;
  height: 14px !important;
  cursor: pointer;

  &:hover {
    color: #00a65b;
  }
}
</style>
